import facade
import requests
from xjlibrary.our_file_dir import BaseDir, ImageFile
from xjlibrary.tools.BaseUrl import BaseUrl

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "sublibbook", "download", "cover")
BaseDir.create_dir(sPath)


class DownCover(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.Baseurl = "http://202.115.72.61:9099/"
        self.mysqlutils = facade.MysqlUtiles(BaseDir.get_new_path(curPath, "db.ini"), "db", self.logger)
        self.proxy = {
            "http": "192.168.30.176:8131",
            "https": "192.168.30.176:8131",
        }
        self.sn = requests.Session()


    def select(self):
        sql = "select url,cover from books where coverstat=0"
        rows = self.mysqlutils.SelectFromDB(sql)
        for row in rows:
            url = row[0]
            cover = row[1]
            cover = cover.replace("99//","99/")
            bookID = BaseUrl.urlQuery2Dict(url)["bookID"]
            pagespath = BaseDir.get_new_path(sPath, bookID + ".jpg")
            if BaseDir.is_file_exists(pagespath):
                sql = "update books set coverstat=1 where url = '{}'".format(url)
                self.mysqlutils.ExeSqlToDB(sql)
                self.logger.info("文件存在："+pagespath)
                continue
            BoolResult, errString, r = facade.BaseRequest(cover,
                                                          sn=self.sn,
                                                          endstring="",
                                                          proxies=self.proxy,
                                                          # headers=self.headers,
                                                          timeout=(30, 60))
            if BoolResult:
                if ImageFile.img_to_format_jpg(r.content, pagespath):
                    sql = "update books set coverstat=1 where url = '{}'".format(url)
                    self.mysqlutils.ExeSqlToDB(sql)
            else:
                self.logger.info("下载图片失败")


if __name__ == "__main__":
    down = DownCover()
    down.select()


